package com.halove.remotelyhelper.common.httputil;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (2012-2016) by 杭州九爱科技有限公司. All rights reserved
 * Comments:用于RecyclerView的数据适配器基类
 * DATA是子元素的类型
 *
 * @author yining
 *         Created on 2016/3/31 13:18
 */
public abstract class BindingRecyclerAdapter<DATA> extends RecyclerView.Adapter<BindingViewHolder> {

    protected List<DATA> data = new ArrayList<>();
    LayoutInflater inflater;
    public BindingRecyclerAdapter() {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception expected) {
            //没有事件注册，无需处理的异常
        }
    }
    @Override
    public BindingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        int resId = getItemLayoutRes(viewType);
        if (resId <= 0) {
            throw new NullPointerException(getClass().getSimpleName() + ".getItemLayoutRes()返回了无效的布局资源ID");
        }
        if (inflater == null)
            inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, resId, parent, false);
        return new BindingViewHolder(binding);
    }
    @Override
    public void onBindViewHolder(BindingViewHolder holder, int position) {
        ViewDataBinding binding = holder.getViewDataBinding();
        bindItem(binding, getItem(position), position, getItemViewType(position));
        //binding.executePendingBindings();
    }
    public abstract void bindItem(ViewDataBinding binding, DATA data, int position, int viewType);
    @Override
    public int getItemCount() {
        return data.size();
    }

    public DATA getItem(int position) {
        return data.get(position);
    }

    public void setData(List<DATA> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    //派生类重载此函数来返回viewType对应的item_layout的资源id
    @LayoutRes
    public abstract int getItemLayoutRes(int viewType);

}
